package com.lb.statck.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Map;
 @Slf4j
@RestController("/api/pay")
public class WeChatPayNotifyController {

    @Value("${wx.miniapp.apiV3Key}")
    private String apiV3Key;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/wechat/notify")
    public Map<String, Object> handleWeChatPayNotify(@RequestBody Map<String, Object> notifyData,
                                                     HttpServletRequest request) throws Exception {

        // 获取请求头中的签名信息
      //  log.info(wechatpayTimestamp);
        String wechatpayTimestamp = request.getHeader("Wechatpay-Timestamp");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatpaySignature = request.getHeader("Wechatpay-Signature");
        System.out.println(wechatpayTimestamp);
        System.out.println(wechatpayNonce);
        System.out.println(wechatpaySignature);
        log.info(wechatpayTimestamp);
        log.info(wechatpayNonce);
        log.info(wechatpaySignature);
        // 构造待验签字符串
        String message = wechatpayTimestamp + "\n" + wechatpayNonce + "\n" + objectMapper.writeValueAsString(notifyData) + "\n";

        // 验签逻辑（需要你有证书公钥）
        if (!verifySignature(message, wechatpaySignature)) {
            throw new RuntimeException("签名验证失败");
        }

        // 解密 resource 数据
        JsonNode resourceNode = objectMapper.readTree(objectMapper.writeValueAsString(notifyData.get("resource")));
        String ciphertext = resourceNode.get("ciphertext").asText();
        String associatedData = resourceNode.has("associated_data") ? resourceNode.get("associated_data").asText() : "";
        String nonce = resourceNode.get("nonce").asText();

        String plainText = decryptToString(associatedData, nonce, ciphertext, apiV3Key);
System.out.println(plainText);

        // 解密后的订单信息
        JsonNode result = objectMapper.readTree(plainText);
        System.out.println("解密结果：" + result);

        // TODO: 在这里添加你的业务逻辑，比如更新数据库订单状态为已支付
      log.info(String.valueOf(result));
        return Map.of("code", "SUCCESS", "message", "成功");
    }

    /**
     * 使用 APIv3 密钥解密数据
     */
    private String decryptToString(String associatedData, String nonce, String ciphertext, String apiV3Key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec(apiV3Key.getBytes(StandardCharsets.UTF_8), "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
        if (associatedData != null && !associatedData.isEmpty()) {
            cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
        }
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 验签方法（简化版，需替换为实际公钥验证）
     */
    private boolean verifySignature(String message, String signature) {
        // 注意：此处仅为演示，应使用商户私钥对 message 签名后与微信签名比对
        // 或使用微信平台公钥进行验签
        System.out.println("签名验证通过");
        return true;
    }
}